<?php
namespace app\forms;

use yii\base\Model;
use app\models\Cate;
use app\models\Bookmark;
class CateForm extends Model
{
    const ERROR_CATENAME_EXISTS = '分类名称已经存在';
    const DEFAULT_COLOR = 'FFFFFF';
    
    const SCENARIO_CREATE = 'create';
    const SCENARIO_RENAME = 'rename';
    const SCENARIO_REMOVE = 'remove';
    
    public $id;
    public $name;
    public $userId;
    
    public function rules() {
        return [
            ['id', 'required', 'on' => [self::SCENARIO_RENAME, self::SCENARIO_REMOVE]],
            ['id', 'number', 'on' => [self::SCENARIO_RENAME, self::SCENARIO_REMOVE]],
            ['name', 'required', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_RENAME]],
            ['userId', 'number', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_RENAME]],
            ['name', 'checkCateName', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_RENAME]]
        ];
    }
    
    public function checkCateName() {
        if (Cate::find()->where(['name' => $this->name])->exists()) {
            $this->addError('name', self::ERROR_CATENAME_EXISTS);
        }
    }
    
    /**
     * 创建一个分类
     * @return \app\models\Cate
     */
    private function create() {
        $cate = new Cate();
        $cate->userId = $this->userId;
        $cate->name = $this->name;
        $cate->color = self::DEFAULT_COLOR;
        $cate->createTime = date('Y-m-d H:i:s');
        
        $cate->save();
        return $cate;
    }
    
    /**
     * 重新命名一个分类
     * @return number
     */
    private function rename() {
        return Cate::updateAll(['name' => $this->name], 'id = :id and userId = :userId', [':id' => $this->id, ':userId' => $this->userId]);
    }
    
    /**
     * 删除一个分类, 和该分类下的所有书签
     * @return number
     */
    private function remove() {
        Bookmark::deleteAll(['cateId' => $this->id, 'userId' => $this->userId]);
        Cate::deleteAll(['id' => $this->id, 'userId' => $this->userId]);
        return true;
    }
    
    public function work() {
        switch ($this->getScenario()) {
            case self::SCENARIO_CREATE:
                return $this->create();
                break;
            case self::SCENARIO_RENAME:
                return $this->rename();
                break;
            case self::SCENARIO_REMOVE:
                return $this->remove();
                break;
            default:
                throw new \RuntimeException('未指定情景');
        }
    }
}

?>